import fs from 'fs'
import bull from 'bull'
import config from '../config'

export const start = () => {
  fs.readdirSync(__dirname).forEach((n,i) => {
    let jobName = n.replace(/\.js$/, '')
    if (jobName == 'index') return
    let jobMdl = require('./' + jobName)
    if (!jobMdl.enable) return

    if (!jobMdl.run) return
    let cctNum = jobMdl.cctNum || 1

    let queue = getQueue(jobName)
    queue.process(cctNum, (job, done) => {
      let {data} = job
      console.info('执行作业', '---', jobName, '---', new Date())
      jobMdl.run(job, data, {}, done).catch(err => {
        console.error(err)
      })
    })
  })
  console.info('jobs queue listener started')
}

const getQueue = (name) => {
  let redisConfig = Object.assign({}, config.queue)
  let t = new bull(name, {redis: redisConfig})
  return t
}

export const add = (type, data = {}, opts = {}) => {
  let queue = getQueue(type)
  let options = Object.assign({
      attempts: 3, removeOnComplete: true
  }, opts)
  queue.add(data, options)
}

export default {
  start,
  add
}
